package com.shelpe.services.sinbad.repository.jpa;

import java.util.Date;
import java.util.List;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;

import com.shelpe.services.sinbad.entity.jpa.Message;

public interface MessageRepository
		extends PagingAndSortingRepository<Message, Long>, JpaSpecificationExecutor<Message> {

	List<Message> findByUserIDAndContainerIDAndUnread(long userID, long containerID, int unread);

	Message findByTypeAndInformID(String type, long informID);

	List<Message> findByUserIDAndTypeAndCreateTimeBeforeOrderByCreateTimeDesc(long userID, String type, Date date);

	Page<Message> findByTypeAndUserIDAndCreateTimeBeforeOrderByCreateTimeDesc(String type, long userID, Date date,
			Pageable page);

	List<Message> findTop3ByMessageTypeOrderByCreateTimeDesc(String messageType);

	@Transactional
	@Modifying
	@Query("delete from user_message_delivery u where u.topicsID = :topics_id")
	int deleteByTopicsID(@Param("topics_id") long topicsID);

	@Transactional
	@Modifying
	@Query(value = "insert into user_message_delivery(user_id, container_id, nick, title, content, container_type, sub_type, topics_id, create_time,last_modife_time) "
			+ "select user_id,user_id,nick,?,?,?,?,?,?,NOW() from users where user_type =1", nativeQuery = true)
	int deliver2messages(String title, String content, String type, String subType, long topicsID, Date createTime);

}
